package cn.tedu.micro.demo.emqx.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqttClientCallback implements MqttCallbackExtended {
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        if(reconnect){
            log.info("重新连接成功,broker地址：{}",serverURI);
        }else{
            log.info("首次链接成功：{}",serverURI);
        }
    }

    @Override
    public void connectionLost(Throwable cause) {
        log.info("连接断开,原因:{}",cause);
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        log.info("消息接收成功,消息:{},来源主题:{}",message,topic);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        boolean complete = token.isComplete();
        MqttException exception = token.getException();
        if(complete&&exception==null){
            log.info("消息发送成功");
        }else{
            log.error("消息发送失败,原因{}",exception);
        }
    }
}
